package utils

import (
	"math/rand"
	"time"
)

func init() {
	rand.New(rand.NewSource(time.Now().UnixNano()))
}

// Retry 重试
func Retry(attempt uint, sleep time.Duration, fn func() error) error {
	if err := fn(); err != nil {
		if attempt--; attempt > 0 {
			sleep += (time.Duration(rand.Int63n(int64(sleep)))) / 2
			time.Sleep(sleep)
			return Retry(attempt, 2*sleep, fn)
		}
		return err
	}
	return nil
}
